import { ModalForm, ProFormTextArea, ProFormUploadButton } from '@ant-design/pro-components';
import { message, Modal, UploadFile } from 'antd';
import { RcFile } from 'antd/lib/upload';
import { useEffect, useState } from 'react';
import { replayUser } from '../service';
import { ComplaintTableItem } from '../types.d';
import { getCompressionFileUrl } from '../utils';

interface ReplayUserProps {
  visible: true;
  complaintId: string;
  close: (newItem?: ComplaintTableItem) => void;
}

// const getBase64 = (file: RcFile): Promise<string> =>
//   new Promise((resolve, reject) => {
//     const reader = new FileReader();
//     reader.readAsDataURL(file);
//     reader.onload = () => resolve(reader.result as string);
//     reader.onerror = (error) => reject(error);
//   });
let fileMap = new Map();
const ReplayUser = (props: ReplayUserProps) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const { visible, complaintId, close } = props;
  useEffect(() => {
    fileMap = new Map();
    return () => {
      fileMap.clear();
    };
  }, []);
  return (
    <ModalForm
      title="回复用户"
      visible={visible}
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
        onCancel: () => {
          close();
        },
      }}
      onFinish={async (values) => {
        if (values?.content?.length < 10) {
          message.warning({ key: 'replay_user', content: '留言字数不可少于10字' });
          return false;
        }
        message.loading({ key: 'replay_user', content: '正在处理，请稍后...' });
        const form = new FormData();
        fileList.forEach((item) => {
          form.append('imgs[]', item as RcFile);
        });
        form.append('content', values.content);
        const res = await replayUser(complaintId, form);
        if (res.success) {
          message.success({
            content: res.message,
            key: 'replay_user',
          });
          close(res.data);
          return true;
        }
        message.error({ content: res.message, key: 'replay_user' });
        return false;
      }}
    >
      <ProFormTextArea
        label="回复内容"
        name="content"
        required
        fieldProps={{
          showCount: true,
          maxLength: 200,
          minLength: 10,
        }}
      />
      <ProFormUploadButton
        label="反馈图片"
        title="选择图片"
        tooltip="仅支持jpg, png, bmp为后缀的图片文件, 最大可上传4张"
        name="imgs"
        accept=".jpg,.png,.bmp"
        listType="picture-card"
        fileList={fileList?.map((item) => {
          return { ...item, thumbUrl: fileMap.get(item.uid) };
        })}
        fieldProps={{
          maxCount: 4,
          customRequest: () => {},
          beforeUpload: async (file: RcFile & { thumbUrl?: string }) => {
            if (fileList.length >= 4) {
              message.warn({
                content: '已达上限, 如需继续上传, 请先删除部分图片',
                key: 'replay_user',
              });
              return false;
            }
            const isLt120K = file.size / 1024 < 120;
            if (!isLt120K) {
              message.warn({ content: '图片文件过大，请上传小于120k的图片', key: 'replay_user' });
              return false;
            }
            const thumbUrl = await getCompressionFileUrl(file);
            fileMap.set(file.uid, thumbUrl);
            setFileList([...fileList, file]);
            return false;
          },
          onRemove: (file) => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            fileMap.delete(file.uid);
            setFileList(() => newFileList);
          },
          onPreview: (file) => {
            setPreviewImage(fileMap.get(file.uid) || '');
            setPreviewOpen(true);
            setPreviewTitle(file.name);
          },
        }}
      />
      <Modal
        open={previewOpen}
        title={previewTitle}
        footer={null}
        onCancel={() => setPreviewOpen(false)}
        style={{ textAlign: 'center' }}
      >
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </ModalForm>
  );
};

export default ReplayUser;
